<template>
  <el-dialog v-model="visible" :title="title" width="80%">
    <!-- PDF -->
    <iframe
      v-if="isPDF(fileUrl)"
      :src="fileUrl"
      width="100%"
      height="600px"
      style="border: none;"
    />

    <!-- 图片 -->
    <el-image
      v-else-if="isImage(fileUrl)"
      :src="fileUrl"
      :preview-src-list="[fileUrl]"
      style="max-width: 100%; height: auto"
    />

    <!-- Word/Excel 使用微软 viewer -->
    <iframe
      v-else-if="isOffice(fileUrl)"
      :src="'https://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(fileUrl)"
      width="100%"
      height="600px"
      frameborder="0"
    />

    <!-- 不支持的类型 -->
    <div v-else>
      暂不支持此类型文件预览：{{ fileUrl }}
    </div>
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'

const visible = ref(false)
const fileUrl = ref('')
const title = ref('文件预览')

function openPreview(url, name = '文件预览') {
  fileUrl.value = url
  title.value = name
  visible.value = true
}

function isPDF(url) {
  return /\.pdf$/i.test(url)
}
function isImage(url) {
  return /\.(png|jpe?g|gif|bmp)$/i.test(url)
}
function isOffice(url) {
  return /\.(docx?|xlsx?)$/i.test(url)
}

defineExpose({ openPreview })
</script>
